package guiTest;

import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

public class MusicTableModel extends AbstractTableModel implements TableModel 
{
	
	public static final String COLUMN_NAMES[] =	{"Song", "Artist", "Rating", "Duration"};
	
	public static final int NUM_COLUMNS = COLUMN_NAMES.length;
	SongData allSongData;
	
	public MusicTableModel(SongData sd)
	{
		allSongData = sd;				
	}
	
	public Song getSong(int rowIndex)
	{
		return allSongData.getSong(rowIndex);		
	}
	
	@Override
	public void addTableModelListener(TableModelListener l) 
	{
		
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) 
	{
		if(columnIndex == 0 || columnIndex == 1)
		{
			return String.class;
		}
		else if(columnIndex == 2)
		{
			return Integer.class;
		}
		else if(columnIndex == 3)
		{
			return Duration.class;
		}
			
		return null;
	}

	@Override
	public int getColumnCount() 
	{
		return NUM_COLUMNS;
	}

	@Override
	public String getColumnName(int columnIndex) 
	{
		if(columnIndex >= 0 && columnIndex < NUM_COLUMNS)
		{
			return COLUMN_NAMES[columnIndex]; 
		}
		
		return null;
	}

	@Override
	public int getRowCount() 
	{
		return allSongData.getNumberOfSongs();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) 
	{
		Song theSong = allSongData.getSong(rowIndex);
		
		if(columnIndex == 0)
		{
			return theSong.getSong();
		}
		else if(columnIndex == 1)
		{
			return theSong.getArtist();			
		}
		else if(columnIndex == 2)
		{
			return theSong.getRating();
		}
		else if(columnIndex == 3)
		{
			return theSong.getDuration();
		}
		
		return null;
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) 
	{
		if(columnIndex == 2)
		{
			return true;
		}
		return false;
	}

	@Override
	public void removeTableModelListener(TableModelListener l) 
	{
				
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) 
	{
		if(columnIndex == 2)
		{
			try
			{
				String k = aValue.toString();
				k.replaceAll("[a-zA-Z]", "");
				
				Integer newRating = new Integer(k);
				if(newRating >= 0 && newRating <= 100)
				{
					//System.out.println("" + aValue.toString() + " (" +  rowIndex + ")");
					allSongData.updateSongRating(newRating, rowIndex);
					fireTableCellUpdated(rowIndex, columnIndex);
					
					//System.out.println("Rating updated to " + aValue.toString() + " for " +
					//		rowIndex);
				}
			}
			catch(Exception e)
			{
								
			}						
		}
		
		return;
	}
	

}
